<template>
  <view class="address-edit-page">
    <form @submit="saveAddress">
      <!-- 联系人信息 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">收货人</text>
          <input 
            class="input" 
            type="text"
            v-model="address.name"
            placeholder="请输入收货人姓名"
          />
        </view>
        <view class="form-item">
          <text class="label">手机号码</text>
          <input 
            class="input" 
            type="number"
            maxlength="11"
            v-model="address.phone"
            placeholder="请输入手机号码"
          />
        </view>
      </view>
      
      <!-- 地区选择 -->
      <view class="form-section">
        <view class="form-item" @click="openRegionPicker">
          <text class="label">所在地区</text>
          <view class="region-picker">
            <text class="region-text" v-if="regionText">{{ regionText }}</text>
            <text class="placeholder" v-else>请选择省/市/区</text>
            <text class="arrow">></text>
          </view>
        </view>
        
        <view class="form-item">
          <text class="label">详细地址</text>
          <textarea 
            class="textarea" 
            v-model="address.detail"
            placeholder="请输入详细地址，如街道、门牌号等"
          />
        </view>
      </view>
      
      <!-- 设为默认地址 -->
      <view class="form-section">
        <view class="form-item switch-item">
          <text class="label">设为默认地址</text>
          <switch 
            :checked="address.isDefault" 
            @change="address.isDefault = $event.detail.value"
            color="#e5394d"
          />
        </view>
      </view>
      
      <!-- 保存按钮 -->
      <view class="save-btn-wrapper">
        <button class="save-btn" form-type="submit" type="primary">保存</button>
      </view>
    </form>
    
    <!-- 地区选择器 -->
    <picker-view
      v-if="showRegionPicker"
      class="region-picker-view"
      :indicator-style="'height: 50px;'"
      :value="regionIndexes"
      @change="onRegionChange"
    >
      <!-- 遮罩层 -->
      <view class="mask" @click="showRegionPicker = false"></view>
      
      <view class="picker-content">
        <view class="picker-header">
          <text class="cancel-btn" @click="showRegionPicker = false">取消</text>
          <text class="title">选择地区</text>
          <text class="confirm-btn" @click="confirmRegion">确定</text>
        </view>
        
        <picker-view-column>
          <view class="picker-item" v-for="(item, index) in provinces" :key="index">
            {{ item.name }}
          </view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-item" v-for="(item, index) in cities" :key="index">
            {{ item.name }}
          </view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-item" v-for="(item, index) in districts" :key="index">
            {{ item.name }}
          </view>
        </picker-view-column>
      </view>
    </picker-view>
  </view>
</template>

<script>
import { mapActions } from 'vuex';
import regionData from '@/utils/region-data.js';
import addressApi from '@/api/address.js';
import '@/styles/pages/address/edit.scss';

export default {
  data() {
    return {
      id: null,
      address: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        isDefault: false
      },
      showRegionPicker: false,
      regionIndexes: [0, 0, 0],
      provinces: regionData,
      cities: regionData[0].children,
      districts: regionData[0].children[0].children
    };
  },
  computed: {
    regionText() {
      if (this.address.province && this.address.city && this.address.district) {
        return `${this.address.province} ${this.address.city} ${this.address.district}`;
      }
      return '';
    },
    isEditing() {
      return !!this.id;
    }
  },
  onLoad(options) {
    // 如果有ID，是编辑状态
    if (options.id) {
      this.id = options.id;
      this.loadAddressData();
    }
    
    // 获取上一页传来的微信地址数据
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('importWxAddress', (wxAddress) => {
      if (wxAddress) {
        this.address = {
          ...this.address,
          ...wxAddress
        };
        this.initRegionIndexes();
      }
    });
  },
  methods: {
    ...mapActions('user', [
      'addAddress',
      'updateAddress'
    ]),
    
    // 加载地址数据
    loadAddressData() {
      uni.showLoading({
        title: '加载中...'
      });
      
      addressApi.getAddressDetail(this.id)
        .then(data => {
          this.address = data;
          this.initRegionIndexes();
        })
        .catch(error => {
          uni.showToast({
            title: '加载地址失败',
            icon: 'none'
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 初始化地区选择器的索引
    initRegionIndexes() {
      // 查找省份索引
      const provinceIndex = this.provinces.findIndex(item => item.name === this.address.province);
      if (provinceIndex !== -1) {
        this.regionIndexes[0] = provinceIndex;
        this.cities = this.provinces[provinceIndex].children || [];
        
        // 查找城市索引
        const cityIndex = this.cities.findIndex(item => item.name === this.address.city);
        if (cityIndex !== -1) {
          this.regionIndexes[1] = cityIndex;
          this.districts = this.cities[cityIndex].children || [];
          
          // 查找区县索引
          const districtIndex = this.districts.findIndex(item => item.name === this.address.district);
          if (districtIndex !== -1) {
            this.regionIndexes[2] = districtIndex;
          }
        }
      }
    },
    
    // 打开地区选择器
    openRegionPicker() {
      this.showRegionPicker = true;
    },
    
    // 地区选择器改变
    onRegionChange(e) {
      const values = e.detail.value;
      
      // 如果省份变了，重置城市和区县
      if (values[0] !== this.regionIndexes[0]) {
        this.cities = this.provinces[values[0]].children || [];
        this.districts = this.cities[0].children || [];
        values[1] = 0;
        values[2] = 0;
      } 
      // 如果城市变了，重置区县
      else if (values[1] !== this.regionIndexes[1]) {
        this.districts = this.cities[values[1]].children || [];
        values[2] = 0;
      }
      
      this.regionIndexes = values;
    },
    
    // 确认地区选择
    confirmRegion() {
      const province = this.provinces[this.regionIndexes[0]];
      const city = this.cities[this.regionIndexes[1]];
      const district = this.districts[this.regionIndexes[2]];
      
      this.address.province = province.name;
      this.address.city = city.name;
      this.address.district = district.name;
      
      this.showRegionPicker = false;
    },
    
    // 保存地址
    saveAddress() {
      // 表单验证
      if (!this.address.name) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        });
        return;
      }
      
      if (!this.address.phone) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        });
        return;
      }
      
      if (!/^1\d{10}$/.test(this.address.phone)) {
        uni.showToast({
          title: '手机号码格式不正确',
          icon: 'none'
        });
        return;
      }
      
      if (!this.address.province || !this.address.city || !this.address.district) {
        uni.showToast({
          title: '请选择所在地区',
          icon: 'none'
        });
        return;
      }
      
      if (!this.address.detail) {
        uni.showToast({
          title: '请输入详细地址',
          icon: 'none'
        });
        return;
      }
      
      // 显示加载中
      uni.showLoading({
        title: '保存中...'
      });
      
      // 调用保存地址API
      const savePromise = this.isEditing ? 
        addressApi.updateAddress(this.address) : 
        addressApi.addAddress(this.address);
        
      savePromise
        .then(() => {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        })
        .catch(() => {
          uni.showToast({
            title: '保存失败，请重试',
            icon: 'none'
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    }
  }
};
</script> 